package com.school.test.search.function.service;

import com.mongodb.client.model.Filters;
import com.school.test.search.function.assist.IndexAssist;
import com.school.test.search.function.assist.MongoListDeal;
import com.school.test.search.function.datamodel.TestModel;
import org.bson.Document;

import java.util.Collection;
import java.util.function.Predicate;
import java.util.regex.Pattern;

/**
 * @author 马洁
 * @date 2020/1/4 - 12:55
 */
public class BaseTeaAndStuService {
    public static void searchInExamListByRegStr(String fieldName, Pattern regStr,
                                         Collection<? super String> resCollection) {
        IndexAssist.getExam()
                .find(Filters.regex(fieldName, regStr))
                .iterator()
                .forEachRemaining(doc -> {
                    MongoListDeal.addToRes(regStr,
                            doc.getList(fieldName, String.class),
                            resCollection);
                });
    }

    public static TestModel dealTestList(Iterable<? extends Document> testSearchList) {
        return dealTestList(testSearchList, null);
    }

    public static TestModel dealTestList(Iterable<? extends Document> testSearchList,
                                         Predicate<? super Document> filter) {
        TestModel resTestListModel = new TestModel();

        if (filter != null) {
            for (Document doc: testSearchList) {
                // 根据过滤条件进行过滤
                if (filter.test(doc)) {
                    dealDoc(doc, resTestListModel);
                    resTestListModel.getTestList().add(doc);
                }
            }
        } else {
            for (Document doc: testSearchList) {
                dealDoc(doc, resTestListModel);
                resTestListModel.getTestList().add(doc);
            }
        }

        return resTestListModel;
    }

    private static void dealDoc(Document doc, final TestModel testModel) {
        // 当前时间戳, 因为Python时间戳为10位, Java多三位, 除法屏蔽掉即可
        long currentTimeMillis = System.currentTimeMillis() / 1000;

        // 小于当前时间的变灰, 即已经考完的考试变灰
        if (doc.getDouble("timestamp") < currentTimeMillis) {
            doc.append("color", "grey");
            doc.append("font_color", "grey");
        } else {
            // 如果未考的计数为0, 则设置最早的考试时间
            if (testModel.getUntestedCount() == 0) {
                testModel.setUntestedStartTime(doc.getDouble("timestamp"));
            }
            // 将其置为可用状态
            doc.append("color", "blue");
            doc.append("font_color", "blue");

            testModel.increaseUntestedCount();
        }
    }
}
